package com.lx.generator.monitor;

import com.lx.idgenerator.segement.policy.IFetchPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author lX
 * @version JDK 8
 * @className TpsMonitor (此处以class为例)
 * @date 2024/11/10
 * @description TODO
 */
public class TpsMonitor {

    Logger logger = LoggerFactory.getLogger(TpsMonitor.class);

    private TpsCounter tpsCounter;


    private IFetchPolicy fetchPolicy;

    public TpsMonitor(TpsCounter tpsCounter, IFetchPolicy fetchPolicy) {
        this.tpsCounter = tpsCounter;
        this.fetchPolicy = fetchPolicy;
        init();
    }

    private void monitorTps() {
        double tps = tpsCounter.getTps();
        fetchPolicy.setTpsThreshold("",tps);

    }

    private void init() {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(() -> {
            try {
                monitorTps();
            } catch (Exception e) {
                logger.error("TPS监控任务执行失败", e);
            }
        }, 0, 1, TimeUnit.SECONDS);
    }


}
